<template>
  <div class="register-container">
    <div class="register-box">
      <h2 class="register-title">注册</h2>
      <form class="register-form" @submit.prevent="onSubmit">
         <div v-if="errorMessage" class="global-error">{{ errorMessage }}</div>
        <input v-model="email" type="email" placeholder="你的邮箱" class="form-input" required/>
        <input v-model="username" type="text" placeholder="用户名" class="form-input" required/>
        <input v-model="password" type="password" placeholder="密码" class="form-input" required/>
        <input v-model="confirmPassword" type="password" placeholder="重复密码" class="form-input" required/>

        <div class="verification-box">
          <input v-model="verificationCode" type="text" placeholder="验证码" class="form-input verification-input"
                 required/>

          <button
              class="verification-button"
              type="button"
              :disabled="countdown > 0"
              @click="getCode"
          >
            {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
          </button>

        </div>
       <button :disabled="loading" class="submit-button" type="submit">{{ loading ? '注册中...' : '注册' }}</button>

      </form>
      <div class="login-tip">
        已有账户？<a href="/login" class="login-link">马上登录</a>
      </div>
    </div>
  </div>
</template>


<script setup>
import { useUserStore } from '@stores/userStore.js'
const store = useUserStore();
const email = ref('');
const username = ref('');
const password = ref('');
const confirmPassword = ref('');
const verificationCode = ref('');
const countdown = ref(0);
const router = useRouter();
let timer = null;
// 新增错误提示响应式变量
const errorMessage = ref('');

const validatePassword = () => {
  const regex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
  return regex.test(password.value);
};

const onSubmit = async () => {
  // 清空旧错误
  errorMessage.value = '';
  // 表单验证逻辑（替换alert为错误提示）
  if (!/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/.test(email.value)) {
    showError('请输入有效的邮箱地址');
    return;
  }
  if (password.value !== confirmPassword.value) {
    showError('两次密码输入不一致');
    return;
  }
  if (!validatePassword()) {
    showError('密码需至少8位且包含字母和数字');
    return;
  }

  try {
    // 实际应替换为API调用
    const response = await fetch('/api/accounts/register/', {
      method: 'POST',
      headers: {
        'X-CSRFToken': store.csrfToken,
        'Content-Type': 'application/json'
      },
      withCredentials: true,
      body: JSON.stringify({
        email: email.value,
        username: username.value,
        password: password.value,
        code: verificationCode.value
      })
    });
    const result = await response.json();
    if (response.ok) {
      alert('注册成功');
      router.push('/login');
    }else {
      // 处理不同错误类型
      const errorMsg = result.code ? '验证码错误' :
                      result.email ? '邮箱已被注册' :
                      result.username ? '用户名已存在' :
                      '注册失败，请检查输入';
      showError(errorMsg);
    }
  } catch (error) {
   showError('注册失败，请稍后重试');
  }
};
// 新增错误显示方法
const showError = (msg) => {
  errorMessage.value = msg;
  setTimeout(() => errorMessage.value = '', 3000);
};
const getCode = async () => {
   if (!/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/.test(email.value)) {
    showError('请输入有效的邮箱地址');
    return;
  }

  if (countdown.value > 0) return;

  try {
    const response = await fetch('/api/accounts/send_verification_code/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: email.value
      })
    });

    if (response.ok) {
      // 启动倒计时
       showError('验证码已发送，请查收邮箱');
      countdown.value = 60;
      timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) clearInterval(timer);
      }, 1000);
    } else {
      const result = await response.json();
      showError(result.email ? '该邮箱已注册' : '验证码发送失败');
    }
  } catch (error) {
    showError('服务不可用，请稍后重试');
  }
};
onMounted(async () => {
  const store = useUserStore()
  // 初始化时获取CSRF令牌
  await store.fetchCSRFToken()
})
</script>


<style scoped>
@import '@/assets/accounts/css/font-awesome.min.css';
/* 容器样式 */
.register-container {
  background-image: url('@/assets/accounts/img/register_bg.jpg');
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-size: cover;
  background-position: center;
  background-color: #f5f7fa;
  background-attachment: fixed;
  position: relative;
}

.register-container::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  z-index: 1;
}

.register-box {
  width: 360px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  text-align: center;
  z-index: 2;
}

/* 标题样式 */
.register-title {
  font-size: 24px;
  color: #FF7F50;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #cccccc;
}

/* 表单样式 */
.register-form {
  display: flex;
  flex-direction: column;
}

/* 输入框样式 */
.form-input {
  width: 100%;
  height: 40px;
  margin-bottom: 15px;
  padding: 0 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 14px;
  outline: none;
  box-sizing: border-box;
}

.form-input:focus {
  border-color: #FF7F50;
}

/* 验证码区域样式 */
.verification-box {
  display: flex;
  align-items: stretch; /* 保证子元素高度一致 */
  margin-bottom: 15px;
}

.verification-input {
  flex: 1; /* 输入框宽度自动填充剩余空间 */
  margin-right: 10px;
  height: 40px; /* 保证高度一致 */
}

.verification-button {
  flex-shrink: 0; /* 不允许缩小 */
  height: 40px; /* 按钮高度和输入框一致 */
  padding: 0 15px;
  font-size: 14px;
  background-color: #5fb878;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  box-sizing: border-box;
}

.verification-button:hover {
  background-color: #509e6c;
}


/* 注册按钮样式 */
.submit-button {
  width: 100%;
  height: 45px;
  background-color: #FF7F50;
  color: #fff;
  font-size: 16px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.submit-button:hover {
  background-color: #FF5722;
}

/* 登录提示和链接样式 */
.login-tip {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}

.login-link {
  color: #33ccff;
  text-decoration: none;
}

.login-link:hover {
  color: #ff5722;
}

/* 错误提示样式 */
/* 增强错误提示样式 */
.global-error {
  color: #ff4d4f;
  padding: 12px;
  background: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 4px;
  margin-bottom: 20px;
  text-align: center;
  animation: fadeOut 3s forwards;
  animation-delay: 2s;
}

@keyframes fadeOut {
  from { opacity: 1; }
  to { opacity: 0; }
}

/* 调整原有错误提示位置 */
.error-message {
  margin: 10px 0;
}


@media (max-width: 480px) {
  .register-container {
    padding: 50px;
    height: calc(100vh + 50px);
  }
  .register-box {
    width: 100%;
    min-width: 300px;
    padding: 15px;
  }
}


</style>

